package com.fw.application.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.annotation.Log;
import com.fw.annotation.PrintParam;
import com.fw.application.controller.base.BaseController;
import com.fw.common.IdXD;
import com.fw.constant.Constant;
import com.fw.core.domain.AjaxResult;
import com.fw.core.domain.model.LoginUser;
import com.fw.core.page.TableDataInfo;
import com.fw.enums.BusinessType;
import com.fw.enums.SpuStatusEnum;
import com.fw.mes.Result;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.model.form.SpuForm;
import com.fw.system.web.model.vo.FootprintVo;
import com.fw.system.web.service.*;
import com.fw.utils.ServletUtils;
import com.fw.utils.StringUtils;
import com.fw.utils.poi.ExcelUtil;
import com.fw.utils.spring.SpringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import static com.fw.mes.ResultUtils.success;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author
 * @since 2021-05-10
 */
@RestController
@RequestMapping("/spu")
@Api(tags = "商品")
public class FwSpuController implements BaseController {
    @Autowired
    private IFwSpuService spuService;
    @Autowired
    private IFwShopService shopService;
    @Autowired
    private IFwSkuService skuService;
    @Autowired
    private IFwImagesService imagesService;
    @Autowired
    private IFwUcjoinService ucjoinService;
    @Autowired
    private IFwSpucateService spucateService;
    @Autowired
    private IFwFootprintService fwFootprintService;
    @Autowired
    private IFwAgentRegionService agentRegionService;
    @Autowired
    private IFwRuleDatasService ruleDatasService;
    @Autowired
    private IdXD idXD;

    /**
     * @Effect 商品列表
     * @Author 姚
     * @Date 2021/6/8
     **/
    @ApiOperation("商品列表")
    @PostMapping("/list")
    public Result<PageInfo<FwSpu>> list(@RequestBody SpuForm spuForm){
        List<String> categoryS = Arrays.asList(spuForm.getCategory().split(","));
        List<Object> categoryList = null;
        if (categoryS.size() > 0)
            categoryList = spucateService.listObjs(Wrappers.<FwSpucate>lambdaQuery()
                    .select(FwSpucate::getId)
                    .in(FwSpucate::getId, categoryS)
                    .or()
                    .in(FwSpucate::getParentId, categoryS));
        PageHelper.startPage(spuForm.getPageNum(),spuForm.getPageSize());
        List<FwSpu> list = spuService.list(Wrappers.<FwSpu>lambdaQuery()
                .eq(spuForm.getIsOffline()!=-1, FwSpu::getIsOffline, spuForm.getIsOffline())
                //  `status` tinyint(1) DEFAULT '0' COMMENT '商品状态 0=正常，1=下架',
                .eq(FwSpu::getStatus, "0")
                .in(categoryS.size() > 0,  FwSpu::getCategory, categoryList)
                .eq(!spuForm.getHotSale().equals(-1),    FwSpu::getHotSale, spuForm.getHotSale())
                .eq(!spuForm.getRecommend().equals(-1),  FwSpu::getRecommend,    spuForm.getRecommend())
                .eq(!spuForm.getIsQuiz().equals(-1),    FwSpu::getIsQuiz,   spuForm.getIsQuiz())
                 .eq(FwSpu::getStatus, SpuStatusEnum.UP_SPU.getCode())
                .eq(!spuForm.getIsSale().equals(-1),    FwSpu::getIsSale,   spuForm.getIsSale())
                .eq(!"".equals(spuForm.getShopId()),    FwSpu::getShopId,   spuForm.getShopId())
                .like(!"".equals(spuForm.getTitle()),   FwSpu::getTitle,    spuForm.getTitle())
                .between(spuForm.getPriceBetween().compareTo(spuForm.getPriceAnd())!=0,
                        FwSpu::getPrice, spuForm.getPriceBetween(), spuForm.getPriceAnd())
                .orderByDesc(spuForm.getOrderByTops() == 0 && spuForm.getOrderByPrice() == 0,
                        FwSpu::getCreateTime)
                .orderBy(spuForm.getOrderByTops()>0, spuForm.getOrderByTops() ==1, FwSpu::getTops)
                .orderBy(spuForm.getOrderByPrice()>0, spuForm.getOrderByPrice()==1, FwSpu::getPrice));
        PageInfo<FwSpu> spuPageInfo = new PageInfo<>(list);
        return success(spuPageInfo);
    }

    /**
     * @Effect 商品详情
     * @Author 姚
     * @Date 2021/6/8
     **/
    @ApiOperation("商品详情")
    @GetMapping("/detail/{id}")
    public Result<Object> detail(@PathVariable String id){
        FwUser user = getDefaultUser();
        FwSpu byId = spuService.getById(id);
        if (byId == null) { return new Result<>().fail(1,"未找到该商品"+id); }
        byId.setFwShop(shopService.getById(byId.getShopId()));
        byId.setFwSkuList(skuService.list(Wrappers.<FwSku>lambdaQuery()
                .eq(FwSku::getSpuId, byId.getId())));
        byId.setFwImages(imagesService.list(Wrappers.<FwImages>lambdaQuery()
                .eq(FwImages::getBusinessId, byId.getId())));
        byId.setIsKeep(0);
        if (user != null) {
            byId.setIsKeep(ucjoinService.count(Wrappers.<FwUcjoin>lambdaQuery()
                    .eq(FwUcjoin::getItemId, id)
                    .eq(FwUcjoin::getUserId, user.getId())));
        }
        //类目名
        FwSpucate spuCate = spucateService.getById(byId.getCategory());
        byId.setCategoryName( spuCate.getCateName() );

        //新增足迹
        if (user != null) {
            fwFootprintService.insertFwFootprint(id,user.getId());
        }
        return success(byId);
    }


    /**
     * 查询足迹列表
     */
    @GetMapping("/footprintList")
    @ApiOperation("查询足迹列表")
    public Result<List<FootprintVo>> footprintList() {
        FwUser user = getUser();
        List<FootprintVo> footprintVos = fwFootprintService.selectFwFootprintList(user.getId());
        return success(footprintVos);
    }

    /**
     * 删除足迹
     */
    @DeleteMapping("footprintRemove/{ids}")
    @ApiOperation("删除足迹")
    public Result footprintRemove(@PathVariable String[] ids) {
        return success(fwFootprintService.deleteFwFootprintByIds(ids));
    }


    @PostMapping("getSaleList")
    @ApiOperation("特卖列表，只传【省市县码】即可")
    public Result<List<FwSpu>> getSaleList(@RequestBody FwSpu spu){
        List<FwSpu> list = spuService.list(Wrappers.<FwSpu>lambdaQuery()
                .eq(FwSpu::getIsSale, 1)
                .eq(FwSpu::getProvince, spu.getProvince())
                .eq(FwSpu::getCity, spu.getCity())
                .eq(FwSpu::getArea, spu.getArea()));
        return success(list);
    }

    /**
     * 添加商品
     */
    @PostMapping("add")
    @ApiOperation("添加商品")
    @PrintParam
    public Result<Object> add(@RequestBody FwSpu spu){
        spu.setId(idXD.nextId());
        //特卖不判断商户
        if (!Integer.valueOf(1).equals(spu.getIsSale())) {
            FwUser user = getDefaultUser();
            if (user == null) {return new Result<>().fail(1,"请重新登录");}
            String shopId = shopService.getOne(Wrappers.<FwShop>lambdaQuery().eq(FwShop::getUserId, user.getId())).getId();
            if (StringUtils.isNotBlank(shopId)) {spu.setShopId(shopId);}

            Assert.isTrue(StringUtils.isNotBlank(spu.getShopId()),"商铺未指定不可添加商品.");
        }

        Result<Object> result = updateAndSave(spu);
        if (result != null) { return result; }
        updateAndSave(spu);
        return success(spuService.save(spu));
    }

    /**
     * 修改商品
     */
    @PostMapping("update")
    @ApiOperation("修改商品")
    @PrintParam
    public Result<Object> update(@RequestBody FwSpu spu){
        Result<Object> result = updateAndSave(spu);
        if (result != null) { return result; }
        if (spu.getStatus() instanceof Integer)
           spu.setStatus(spuService.getById(spu.getId()).getStatus()) ;
        return success(spuService.updateById(spu));
    }

    /**
     * 更新或新增时验证的一些东西，后管有个一摸一样的方法，改的时候要同步修改
     *
     * @param fwSpu
     * @return Result<Object>
     * @author 姚自强
     * @date 2021/8/10
     */
    private Result<Object> updateAndSave(FwSpu fwSpu) {
        //让利大于0.01，线下除外
        if (fwSpu.getPrice().compareTo(BigDecimal.valueOf(0.01)) < 0 && "0".equals(fwSpu.getIsOffline()))
            { return new Result<>().fail(1,"让利不可低于0.01"); }
        //线下除外
        if (fwSpu.getRealPrice().compareTo(fwSpu.getPrice()) < 0 && "0".equals(fwSpu.getIsOffline()))
            { return new Result<>().fail(1,"当前售价不可低于让利"); }
        BigDecimal divide = fwSpu.getPrice().divide(fwSpu.getRealPrice(), 3, BigDecimal.ROUND_HALF_EVEN);
        if ("0".equals(fwSpu.getIsOffline())) {
            if (fwSpu.getIsQuiz() != null && fwSpu.getIsQuiz() == 1) {
                if ( divide.compareTo(BigDecimal.valueOf(0.35)) < 0) {
                    return new Result<>().fail(1,"成为竞猜商品，让利值需大于售价的35%");
                }
            } else {
                //特卖商品不做判断
                if (Integer.valueOf(0).equals(fwSpu.getIsOffline())) {
                    if (!Integer.valueOf(1).equals(fwSpu.getIsSale()) && divide.compareTo(BigDecimal.valueOf(0.2)) < 0) {
                        return new Result<>().fail(1,"提交商品，让利值需大于售价的20%");
                    }
                }

            }
        }

        //特卖验证
        if (Integer.valueOf(1).equals(fwSpu.getIsSale())) {
            // 获取当前的用户
            FwUser user = getDefaultUser();
            if (user == null) {return new Result<>().fail(1,"请重新登录");}
            FwAgentRegion agentRegion = agentRegionService.getOne(Wrappers.<FwAgentRegion>lambdaQuery()
                    .eq(FwAgentRegion::getUserId, user.getId())
                    .eq(FwAgentRegion::getAgent, Constant.IsRuleData.AREA_VIP_MONEY_ID)
                    .eq(FwAgentRegion::getIsDefault, 1));
            if (agentRegion == null) {return new Result<>().fail(1,"仅区县代理可以操作特卖商品");}
            //本代理范围是否已存在特卖商品
            FwSpu saleSpu = spuService.getOne(Wrappers.<FwSpu>lambdaQuery()
                    .eq(FwSpu::getIsSale, 1)
                    .eq(FwSpu::getProvince, agentRegion.getProvince())
                    .eq(FwSpu::getCity, agentRegion.getCity())
                    .eq(FwSpu::getArea, agentRegion.getArea()));
            if (saleSpu != null && ! fwSpu.getId().equals(saleSpu.getId())){
                //说明已存在特卖商品 id不等，不是修改，额外加了一个特卖
                return new Result<>().fail(1,"同地区仅可存在一个特卖商品");
            }

            //填充省市县
            fwSpu.setProvince( agentRegion.getProvince() );
            fwSpu.setCity( agentRegion.getCity() );
            fwSpu.setArea( agentRegion.getArea() );
        }


        //计算消证
        BigDecimal bigDecimal = ruleDatasService.getBigDecimal(Constant.IsRuleData.ONLINE_DISAPPEAR_MAGNIFICATION);
        if (fwSpu.getIsQuiz() != null && fwSpu.getIsQuiz() == 1) {
            fwSpu.setDisappear( fwSpu.getRealPrice() );
        } else {
            fwSpu.setDisappear( fwSpu.getPrice().multiply(bigDecimal) );
        }

        //验证质押商甲
        if (fwSpu.getShopId() != null) {
            if ("1".equals(fwSpu.getIsOffline())) {
                shopService.shopPublishSpu(fwSpu.getShopId(),Constant.ShopRuleData.SHOP_SHANGJIA_OFFLINE);
            }else{
                shopService.shopPublishSpu(fwSpu.getShopId(),Constant.ShopRuleData.SHOP_SHANGJIA_ONLINE);
            }
        }


        //图片
        imagesService.remove(Wrappers.<FwImages>lambdaQuery().eq(FwImages::getBusinessId, fwSpu.getId()));
        fwSpu.getImages().forEach(image -> {
            image.setId(idXD.nextId());
            image.setBusinessId( fwSpu.getId() );
            image.setStatus(1);
        } );
        imagesService.saveBatch( fwSpu.getImages() );

        //规格
        fwSpu.setBalance(0);
        skuService.remove( Wrappers.<FwSku>lambdaQuery().eq(FwSku::getSpuId, fwSpu.getId()) );
        fwSpu.getSkuList().forEach(sku->{
            sku.setId(idXD.nextId() );
            sku.setSpuId( fwSpu.getId() );
            fwSpu.setBalance(fwSpu.getBalance() + sku.getSkuBalance() )  ;
        } );
        skuService.saveBatch( fwSpu.getSkuList() );
        return null;
    }

    @PostMapping("delete")
    @ApiOperation("删除商品")
    public Result<Object> delete(String spuId){
        FwSpu spu = spuService.getById(spuId);
        if (spu == null) {
            return new Result<>().fail(1,"未找到该商品->"+spuId);
        }
        spuService.removeById(spuId);
        return success("删除成功");
    }
}

